<?php
namespace frontend\controllers;

use frontend\models\User;
use Yii;
use frontend\models\LoginForm;
use frontend\models\BundingForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\Exception;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frontend\components\SaeTOAuthV2;
use frontend\models\UserOauth;
/**
 * Site controller
 */
class LoginController extends Controller
{
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }
    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->renderPartial('@views/index',['modelOne'=>new SignupForm(),'modelTwo'=>new LoginForm()]);
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        //var_dump(Yii::$app->request->post());die;
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('@views/index', [
                'modelTwo' => $model,
                'modelOne'=>new SignupForm()
            ]);
        }
    }
    public function actionOauth($oauth=1){
        switch($oauth){
            case 1:
                $o = new SaeTOAuthV2( Yii::$app->params['components']['appKey'] , Yii::$app->params['components']['appSecret'] );
                $code_url = $o->getAuthorizeURL( Yii::$app->params['components']['callBack'] );
                return $this->redirect($code_url);break;
        }
    }
    public function actionCallback(){
        $o = new SaeTOAuthV2( Yii::$app->params['components']['appKey'] , Yii::$app->params['components']['appSecret'] );
        $keys['code']=Yii::$app->request->get('code');
        $keys['redirect_uri'] =Yii::$app->params['components']['callBack'];
        $token=$o->getAccessToken( 'code', $keys );
       if($token){
            $model=new UserOauth();
           //print_r($model->getOne($token['uid']));die;
            if($model->getOne($token['uid'])){
               return $this->LoginT($token['uid']);
            }
           $modelU=new SignupForm();
           $arr=[
               '_scrf-frontend'=>Yii::$app->request->getCsrfToken(),
               	'SignupForm' => [
                    'username' => 'sina_'.date("Ymd").mt_rand(100000,999999).$token['uid'],
                    'email' => mt_rand(100000,999999).'@yii.com',
                    'password' => Yii::$app->params['sinaWB']['sina_user_password'],
                ],
               'signup-button' => ''
           ];
           if($modelU->load($arr)&&$user=$modelU->signup()){
               if(Yii::$app->getUser()->login($user)){
                   $userOauth = new UserOauth;
                   $userOauth->open_id = $token['uid'];
                   $userOauth->type = 1;
                   $userOauth->user_id = Yii::$app->user->getId();
                   $userOauth->create_time = time();
                   $userOauth->password = Yii::$app->params['sinaWB']['sina_user_password'];
                   $userOauth->nickname = '新浪微博用户';
                   $userOauth->save();
               }
           }
           return $this->redirect(\yii\helpers\Url::to(['login/bunding', 'oauthUser' => urlencode(base64_encode($userOauth->user_id))]));
       }
    }
    public function LoginT($uid){
        $model=UserOauth::find()->where(['open_id'=>$uid])->one();
        $modelU=new UserOauth();
        $arr=$model->loginOne;
        $data=array(
            '_csrf-frontend'=>Yii::$app->request->getCsrfToken(),
            'BundingForm'=>[
                'username'=>$arr['username'],
                'password'=>$modelU->getOne($uid)['password'],
            ],
            'bunding-button'=>''
        );
        $Login=new BundingForm();
        if($Login->load($data) && $Login->login()){
            return $this->render('@views/index', [
                'modelOne' =>new SignupForm(),
                'modelTwo'=>new LoginForm()
            ]);
        }
    }
    public function actionBunding($oauthUser=0){
        $model=new BundingForm();
        if(Yii::$app->request->isPost){
            $data=Yii::$app->request->post();
            if ($model->load($data)&&$model->login()) {
                $uid=base64_decode($oauthUser);
                $modelOauth=UserOauth::findOne(['user_id'=>$uid]);
               // print_r($modelOauth);die;
                $modelOauth->user_id=Yii::$app->user->getId();
                $modelOauth->password=$data['BundingForm']['password'];
                $user=User::findOne(['id'=>$modelOauth->user_id]);
                $user->bunding=1;
                if($modelOauth->save()&&User::findOne(['id'=>$uid])->delete()&&$user->save()){
                    return $this->render('@views/index',['modelOne' =>new SignupForm(),
                        'modelTwo'=>new LoginForm()]);
                }
            }
        }
        return $this->render('@views/power',['model'=>$model,'oauthUser'=>$oauthUser]);
    }
    public function actionBundingNo(){
        return $this->render('@views/index', [
            'modelTwo' => new LoginForm(),
            'modelOne'=>new SignupForm()
        ]);
    }
    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->renderPartial('@views/index',['modelOne'=>new SignupForm(),'modelTwo'=>new LoginForm()]);
    }


    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('@views/index', [
            'modelOne' => $model,
            'modelTwo'=>new LoginForm()
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }
        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}
